﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ConsolidationTool.Common;
using System.Collections.Generic;
using ConsolidationTool.WebParts.ControlTemplates;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

namespace ConsolidationTool.WebParts.Layouts.CReport.Forecast
{
    public partial class DillReport : DillReportBase
    {
        public override CommonEntitySelector TopSelector
        {
            get
            {
                return commonEntitySelector as ControlTemplates.CommonEntitySelector;
            }
        }
        public override Repeater BaseReport
        {
            get
            {
                return EQRepeater;
            }
        }
        public override void BeforLoad()
        {
            base.BeforLoad();
            title.Text = PageTitle;
        }

        public override void GenerateReport_Click(object sender, EventArgs e)
        {
            base.GenerateReport_Click(sender, e);
            //base.BeforLoad();
            //InitBaseInfo();

            ReceiveEntityData(TopSelector.drpEntity.SelectedValue, CEntity.SelectedDateTime.Year, CEntity.SelectedDateTime.Month, ForecastListTitle, true);

            for (int i = 1; i <= CEntity.SelectedDateTime.Month; i++)
            {
                ReceiveEntityData(TopSelector.drpEntity.SelectedValue, CEntity.SelectedDateTime.Year, i, ActualListTitle, false);
            }

            AfterDataLoaded();

        }

        public override void ReceiveEntityData(string coCd, int year, int month, string listTitle, bool forecast)
        {
            SPListItem it = Common.BusinessService.GetItem("", year, month, listTitle);

            if (it != null)
            {
                string currency = it["Currency"] + "";
                string BillData = it["BillData"] + "";

                var Relationships = new JavaScriptSerializer().Deserialize<List<fsentity>>(BillData);

                Relationships.Where(p => !p.controlrow).ToList().ForEach(p =>
                {
                    if (p.emptyrow && forecast)
                    {
                        //  if (month == 1)
                        //  {
                        var empty = new RQDataItem();
                        if (!string.IsNullOrEmpty(p.description) && p.accountcode.ToUpper().Trim() != "CONTROL")
                        {
                            empty.acountcode = p.description;
                        }

                        TableData.Add(empty);
                        // }
                    }
                    else
                        CreateKoInstance(month, currency, p, forecast, 0);
                });
            }
            else
            {

                TableData.ForEach(p =>
                {
                    if (p.head == null && p.values.Count > 0)
                        p.values.Insert(p.values.Count - 3, "");
                });
            }

        }


        public override void CreateKoInstance(int month, string currency, fsentity p, bool forecast, int index)
        {
            bool fieldExist = true;
            var fixedIdentity = !p.accountcode.IsNullOrEmpty() ? (p.accountcode + "").Substring(4) : "undefined";

            var ins = TableData.FirstOrDefault(a => !a.acountcode.IsNullOrEmpty() && (a.acountcode + "").Substring(4) == fixedIdentity);
            if (ins == null)
            {
                fieldExist = forecast ? false : true;
                ins = new RQDataItem();
                ins.acountcode = p.accountcode;
                ins.title = p.description;
                ins.unit = p.unit;
            }
            //if (!string.IsNullOrEmpty(p.CM))
            //{
            //if (fieldValue.IndexOf('.') != -1)
            //{
            //    string left = decimal.Parse(fieldValue.Split('.')[0]).ToString("N0");
            //    fieldValue = left + "." + fieldValue.Split('.')[1];
            //}
            //else
            //    fieldValue = decimal.Parse(fieldValue).ToString("N0");

            // ins.values.Add(string.IsNullOrEmpty(p.CM) ? "0" : p.CM);
            //}
            if (!forecast)
            {
                if (ins.values.Count == 0) return;
                ins.values.Insert(month - 1, string.IsNullOrEmpty(p.CM) ? "0" : p.CM);
            }
            else
            {
                ins.values.Add(string.IsNullOrEmpty(p.M_1) ? "0" : p.M_1);
                ins.values.Add(string.IsNullOrEmpty(p.M_2) ? "0" : p.M_2);
                ins.values.Add(string.IsNullOrEmpty(p.M_3) ? "0" : p.M_3);
            }

            if (!fieldExist)
            {
                if (p.bold)
                    ins.title = string.Format("<strong>{0}</strong>", ins.title);

                TableData.Add(ins);
            }


        }


        private void InitBaseInfo()
        {
            var topHeaderRow = new RQDataItem() { head = "thead='true'", acountcode = "Accountcode", title = "Description", unit = "Unit" };
            var secondHeaderRow = new RQDataItem() { head = "thead='true'" };

            var startDate = CEntity.SelectedDateTime.AddMonths(-(CEntity.SelectedDateTime.Month - 1));

            for (int i = 0; i < CEntity.SelectedDateTime.Month + 3; i++)
            {
                topHeaderRow.values.Add(startDate.AddMonths(i).ToString("yyyy.MM"));
                secondHeaderRow.values.Add(i < CEntity.SelectedDateTime.Month ? "Actual" : "Forecast");
            }
            TableData.Add(topHeaderRow);
            TableData.Add(secondHeaderRow);
        }
    }
}
